import dayjs from "dayjs"
import { removeConfigLayout } from "@/utils/cache/local-storage"

/** 格式化时间 */
export const formatDateTime = (time: string | number | Date) => {
  return time ? dayjs(new Date(time)).format("YYYY-MM-DD HH:mm:ss") : "N/A"
}

/**
 * @functionName 时间转换
 * @param {Object|string|number} time
 * @param {string} cFormat {y}-{m}-{d} {h}:{i}:{s}
 * @description 返回字符串
 * @author 谭人杰
 * @date 2020-06-10 11:03:20
 */
export function parseTime(time: string | number | Date, cFormat: string): string {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}"
  let date
  if (typeof time === "object") {
    date = time
  } else {
    if (typeof time === "string") {
      if (/^[0-9]+$/.test(time)) {
        time = parseInt(time)
      } else {
        time = time.replace(new RegExp(/-/gm), "/")
      }
    }

    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value]
    }
    return value.toString().padStart(2, "0")
  })
  return time_str
}

/**
 * @description 下载文件
 * @author 谭人杰
 * @date 2024-01-03 19:00:00
 */
export function exportFile(res: string, name: string, isAddTime = true, isLink: boolean = false) {
  const downloadElement = document.createElement("a")
  let href = ""
  if (!isLink) {
    const blob = new Blob([res], {
      type: "application/vnd.ms-excel;charset=utf-8"
    })
    href = window.URL.createObjectURL(blob) //创建下载的链接
  } else {
    href = res
  }
  downloadElement.href = href
  let temp = ""
  if (isAddTime) {
    temp = parseTime(new Date(), "{y}{m}{d}")
  }
  console.log(name)
  downloadElement.download = `${name}${temp}.xls` //下载后文件名
  document.body.appendChild(downloadElement)
  downloadElement.click() //点击下载
  document.body.removeChild(downloadElement) //下载完成移除元素
  window.URL.revokeObjectURL(href) //释放掉blob对象
}

/**
 * @description 将HTML字符串处理成ASP抽象树结构
 * @author 谭人杰
 * @date 2024-01-03 18:59:27
 */
export function getTags(htmlString: string): [] | any[] {
  const parser = new DOMParser()
  const doc = parser.parseFromString(htmlString, "text/html")
  const aTags = doc.querySelectorAll("a")
  const aTagsData = Array.from(aTags).map((a) => {
    return {
      attr: {
        href: a.getAttribute("href"),
        title: a.getAttribute("title"),
        target: a.getAttribute("target")
      },
      tag: a.tagName.toLowerCase(),
      content: a.innerHTML
    }
  })
  return aTagsData
}

/** 用 JS 获取全局 css 变量 */
export const getCssVariableValue = (cssVariableName: string) => {
  let cssVariableValue = ""
  try {
    // 没有拿到值时，会返回空串
    cssVariableValue = getComputedStyle(document.documentElement).getPropertyValue(cssVariableName)
  } catch (error) {
    console.error(error)
  }
  return cssVariableValue
}

/** 用 JS 设置全局 CSS 变量 */
export const setCssVariableValue = (cssVariableName: string, cssVariableValue: string) => {
  try {
    document.documentElement.style.setProperty(cssVariableName, cssVariableValue)
  } catch (error) {
    console.error(error)
  }
}

/** 重置项目配置 */
export const resetConfigLayout = () => {
  removeConfigLayout()
  location.reload()
}
